package com.chocus.core.controller;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chocus.common.utils.RequestUtils;
import com.chocus.common.web.Constants;
import com.chocus.core.bean.BuyerCart;
import com.chocus.core.bean.BuyerItem;
import com.chocus.core.bean.product.Brand;
import com.chocus.core.bean.product.Color;
import com.chocus.core.bean.product.Product;
import com.chocus.core.bean.product.Sku;
import com.chocus.core.service.buyer.BuyerService;
import com.chocus.core.service.buyer.SessionProvider;
import com.chocus.core.service.cms.CmsService;
import com.chocus.core.service.product.ProductService;
import com.chocus.core.service.solr.SolrService;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.itcast.common.page.Pagination;

@Controller
@RequestMapping("/product/")
public class ProductController {

	@Autowired
	private SolrService solrService;
	@Autowired
	private ProductService productService;
	@Autowired
	private CmsService cmsService;
	@Autowired
	private SessionProvider sessionProvider;
	@Autowired
	private BuyerService buyerService;

	@RequestMapping("detail")
	public String detail(Long productId, Model model) {
		Product product = cmsService.getProduct(productId);
		model.addAttribute("product", product);
		List<Sku> skus = cmsService.getSkuByProductId(productId);
		model.addAttribute("skus", skus);
		Set<Color> colors = new HashSet<Color>();
		for (Sku sku : skus) {
			colors.add(sku.getColor());
		}
		model.addAttribute("colors", colors);
		return "product/productDetail";
	}

	/**
	 * 显示列表
	 * 
	 * @param keyWord
	 * @param pageNo
	 * @param model
	 * @return
	 */
	@RequestMapping("list")
	public String list(String keyWord, Integer pageNo, Model model, Long brandId, String price) {
		// 显示品牌筛选列表
		List<Brand> brands = productService.getBrandlistFromRedis();
		model.addAttribute("brands", brands);
		// 所有数据
		Pagination pagination = solrService.getPaginationBySolr(keyWord, pageNo, brandId, price);
		model.addAttribute("pagination", pagination);
		// 控制点击的选项显示在已选条件上
		Map<String, String> map = new TreeMap<String, String>();
		if (brandId != null) {
			for (Brand brand : brands) {
				if (brand.getId() == brandId) {
					map.put("品牌", brand.getName());
					break;
				}
			}
		}
		if (price != null) {
			// 100-200
			String[] split = price.split("-");
			if (split.length == 2) {
				map.put("价格", price);
			} else {
				// 600以上
				map.put("价格", price + "以上");
			}
		}
		model.addAttribute("map", map);
		// 控制被点击的选项不显示
		model.addAttribute("brandId", brandId);
		model.addAttribute("price", price);
		return "product/product";
	}

	/**
	 * 点击购买进入购物车
	 * 
	 * @param skuId
	 * @param amount
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@RequestMapping("buyerCart")
	public String buyerCart(Long skuId, Integer amount, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 用于将json转为对象
		ObjectMapper om = new ObjectMapper();
		om.setSerializationInclusion(Include.NON_NULL);

		BuyerCart buyerCart = null;

		// 1：获取Cookie中购物车
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (Constants.BUYER_CART.equals(cookie.getName())) {
					buyerCart = om.readValue(cookie.getValue(), BuyerCart.class);
				}
			}
		}
		// 2：判断是否有购物车
		if (buyerCart == null) {
			// 3：没有 创建购物车
			buyerCart = new BuyerCart();
		}
		// 4：追加商品到购物车
		if (skuId != null && amount != null) {
			BuyerItem buyerItem = new BuyerItem();
			Sku sku = new Sku();
			sku.setId(skuId);
			buyerItem.setSku(sku);
			buyerItem.setAmount(amount);
			buyerCart.setItem(buyerItem);
		}
		// 5：判断用户是否登陆
		String username = sessionProvider.getAttribute(RequestUtils.getCSESSIONID(request, response));
		// 6：非登陆
		if (username == null) {
			StringWriter w = new StringWriter();
			om.writeValue(w, buyerCart);
			// 创建新Cookie
			// 购物车放到Cookie中
			Cookie cookie = new Cookie(Constants.BUYER_CART, w.toString());
			cookie.setPath("/");
			cookie.setMaxAge(60 * 30);
			// 把Cookie写回浏览器
			response.addCookie(cookie);
		} else {
			// 7：登陆
			// 整个购物车全追加到Redis
			buyerService.addBuyerCartToRedis(buyerCart, username);
			//清空cookie
			Cookie cookie = new Cookie(Constants.BUYER_CART, null);
			cookie.setPath("/");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		return "redirect:toCart";
	}

	/**
	 * 前往购物车页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toCart")
	public String toCart(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		ObjectMapper om = new ObjectMapper();
		om.setSerializationInclusion(Include.NON_NULL);
		BuyerCart buyerCart = null;
		//获取cookie中所有商品添加到redis
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (Constants.BUYER_CART.equals(cookie.getName())) {
					buyerCart = om.readValue(cookie.getValue(), BuyerCart.class);
				}
			}
		}
		// 1、 判断用户是否登陆
		String username = sessionProvider.getAttribute(RequestUtils.getCSESSIONID(request, response));
		if (username != null) {
			buyerService.addBuyerCartToRedis(buyerCart, username);
			//清空cookie
			Cookie cookie = new Cookie(Constants.BUYER_CART, null);
			cookie.setPath("/");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
			// 3、 登陆获取Redis中购物车
			buyerCart = buyerService.getBuyerCartFromRedis(username);
		}
		// 4、 给购物车加载数据
		if(buyerCart != null){
			List<BuyerItem> items = buyerCart.getItems();
			if (items != null && items.size() > 0) {
				for (BuyerItem buyerItem : items) {
					Sku sku = buyerService.putDataToBuyerCart(buyerItem);
					buyerItem.setSku(sku);
				}
			}
		}
		// 5、 回显
		model.addAttribute("buyerCart", buyerCart);
		return "product/cart";
	}
}
